package com.zlx.mall.basic.common.configuration;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author qingke
 **/
@Configuration
public class ThreadPoolConfiguration {

    /**
     * 线程池创建线程流程:
     * 1. 核心线程池已满?
     * 2. 队列已满?
     * 3. 线程池最大容量已满?
     * 4. 抛弃策略
     * @return Executor
     */
    @Bean
    public ExecutorService threadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2 * Runtime.getRuntime().availableProcessors() + 1);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(512);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("thread-pool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return TtlExecutors.getTtlExecutorService(executor.getThreadPoolExecutor());
    }
}
